var PAGE;
var PARAMETERS;
var GET;

function action(functionToCall,form)
{	
    //console.log(PARAMETERS);
    /*var x= event.target||window.event.srcElement; 
    if(x!=null)
    {
        var sender = x.id;
        console.log(x.id); //just for loggin purposes
    }*/

    var idList = getIds();
    var json="";
	
    if(form==undefined)
        json =  {
            "ids":idList,
            "parameters":PARAMETERS,
            "get":GET
        };
    else
        json =  {
            "ids":idList,
            "form":form,
            "parameters":PARAMETERS,
            "get":GET
        };
		
    var jsonString = $.stringify(json);
    //alert("IN: "+jsonString);
    $.post("framework/framework.php",{action:functionToCall,page:PAGE,"json":jsonString},function(data){

        try{
            
            var obj = $.parseJSON(data);
            //alert("OUT: "+data);
            if(obj.redirect != "")  //check if a redirect is requested. If so, do it.
                Redirect(obj.redirect);
            if(obj.permissions != "") //check if they never had permissions to the page
                NoPermissions(obj.permissions);
			
            LoadDynamicJS();
            AssignIdsHtml(obj);
            PARAMETERS = new Array(); // to reset it
	}
        catch(err)
        {
            $("body").html(data);
            //alert(data);
        }
    });
}

/***
 * Sets HTML after a Server request
 * @param obj - JSON object.
 */
function AssignIdsHtml(obj)
{
    $.each(obj.ids, function(key,value){
        
        //$("#"+key).html(value.html); ----> For some reason this would put "" around html.
        document.getElementById(key).innerHTML = value.html;    
        $("#"+key).val(value.val);
        if(value.addClass!="")
            $("#"+key).addClass(value.addClass);
        if(value.removeClass!="")
            $("#"+key).removeClass(value.removeClass);
   });
}

/***
 * Cyles through HTML and gathers all of the ids
 * @returns {Array}
 */
function getIds()
{
    var idList = new Array();
    var json;
		
    $('body [id]').each(function() { //Get elements that have an id=
        if(this.id.indexOf("csscan")==-1)
        {
            var temp = new Object();
            temp.id = $(this).attr("id");
            temp.html = ($(this).html() != "" && $(this).html()!=null) ? $(this).html(): "";
            temp.val = ($(this).val() != "" && $(this).val()!=null) ? $(this).val(): ""; //if the val() is not set, make sure it's ""
            temp.addClass = "";
            temp.removeClass = "";
            idList.push(temp); //add object to array
        }
    });	
    return idList;
}

function NoPermissions(message)
{
    alert(message);
    window.location = "index.php#page=home";
}

/***
 * Redirect to the specified URL
 * @param link URL to redirect to
 */
function Redirect(link)
{
    location.hash=link;
}

/**
 * Set up listener for all forms on page. MUST be called after the page has been loaded.
 */
function SetUp_FormListener()
{
    $('form').submit(function() { 
		
        var namesList = {};
		
        $(this).find(":input").each(function(){
            
            var temp = new Object();
            temp.id = $(this).attr("id");
            temp.html = ($(this).html() != "" && $(this).html()!=null) ? $(this).html(): "";
            temp.val = ($(this).val() != "" && $(this).val()!=null) ? $(this).val(): ""; //if the val() is not set, make sure it's ""
            temp.addClass = "";
            temp.removeClass = "";
            
            if($(this).attr("name")==undefined && $(this).attr("type")=="submit") //forget to put the name. Typtical for submit buttons.
                this.name = "submit";
            
            namesList[this.name]= temp;

        });
	   		   	
        action(namesList.request.val,namesList);
	   	
        return false;//to prevent normal form submission 
    });
}

/**
 * After initial page check, comes here to load the appropriate file
 * 
 */
function On_Load()
{
    $(".dynamic").fadeOut(0);
    $(".dynamic").load(PAGE+".php", function(){

        SetUp_FormListener();
        
        action("Page_Load");
        
       /* $(".dynamic").show("slide", { direction: "left" }, 500, function(){
            $('.scroll').jScrollPane();
        });
        */
        $(".dynamic").fadeIn(500, function(){
            $('.scroll').jScrollPane();
        });
        
        
    });
}

/**
 * - Call when a page loads. Either happens on initial load (when the document is ready), or 
 * When the fragment changes (hashchange event).
 * - Both of these events are below under JQUERY BINDINGS
 */
function Load()
{
    var url = $.url();
    PAGE = url.fparam("page"); 
    GET = url.fparam(); //grab all of the paramaters
    var file = url.attr("file");
	
    if(PAGE == undefined || PAGE =="" || file == "") //If nothing set, do Default
        window.location = "index.php#page=home";
	
    On_Load();
}
function LoadDynamicJS()
{
    $.getScript("Framework/dynamicJS.js")
}

///  JQUERY BINDINGS
$(document).ready(function() {
	
    Load();
		
});

$(window).hashchange( function(){
	
    Load();

});

